package com.xiaoluo.common.k8s;

import com.squareup.okhttp.*;
import com.xiaoluo.common.ssl.XLTrustManager;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.springframework.util.Assert;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.Proxy;

/**
 * Project : XL-CD
 * Package : com.xiaoluo.common.k8s
 * Created by Willian.
 * Date  : 2016/2/1 10:33.
 */
public class KubernetesClientFactory {

    private final static Integer REQUEST_TIMEOUT = 5*60 * 1000;
    private final static Integer CONNECTION_TIMEOUT = 5*60 * 1000;
    //connectionTimeout

    /**
     * 生成k8s client.
     * @param masterUrl
     * @param userName
     * @param password
     * @return
     * @throws Exception
     */
    public static DefaultKubernetesClient newClient(String masterUrl, final String userName, final String password) throws Exception{
        Assert.notNull(masterUrl);

        if(masterUrl.startsWith("https")){
            //ssl
            OkHttpClient httpclient = new OkHttpClient();
            SSLContext e = SSLContext.getInstance("TLS");
            e.init(null, new TrustManager[]{new XLTrustManager()}, null);
            httpclient.setSslSocketFactory(e.getSocketFactory());
            //鉴权
            if(userName != null && !userName.equals("")){
                httpclient.setAuthenticator(new K8sAuthenticator(userName,password));
                //生成k8s's Client
                io.fabric8.kubernetes.client.Config config = new Config();
                config.setMasterUrl(masterUrl);
                config.setRequestTimeout(REQUEST_TIMEOUT);
                config.setConnectionTimeout(CONNECTION_TIMEOUT);
                return new DefaultKubernetesClient(httpclient,config);
            }else {
                return new DefaultKubernetesClient(masterUrl);
            }
        }else {
            //鉴权
            OkHttpClient httpclient = new OkHttpClient();
            if(userName != null && !userName.equals("")){
                httpclient.setAuthenticator(new K8sAuthenticator(userName,password));
                //生成k8s's Client
                io.fabric8.kubernetes.client.Config config = new Config();
                config.setMasterUrl(masterUrl);
                config.setRequestTimeout(REQUEST_TIMEOUT);
                config.setConnectionTimeout(CONNECTION_TIMEOUT);
                return new DefaultKubernetesClient(httpclient,config);
            }else {
                return new DefaultKubernetesClient(masterUrl);
            }
        }
    }
}
